# encoding: utf-8
class Admin::TrafficsController < AdminController

  include TrafficConvert
  respond_to :html, :json
  set_tab :statistics, only: [:stat, :search]
  before_filter :setup, only: [:stat, :search]

  def detail
    @traffics = Traffic.includes(:device)
    @traffics = @traffics.by_device_id(params[:device_id]) unless params[:device_id].blank?
    @traffics = @traffics.before_date(params[:end_date]) unless params[:end_date].blank?
    @traffics = @traffics.after_date(params[:start_date]) unless params[:start_date].blank?
    @traffics = @traffics.order('created_at desc')

    respond_to do |format|
      format.html {
        @traffics = @traffics.page(params[:page]).per(10)
      }
      format.js {
        @traffics = @traffics.page(params[:page]).per(10)
      }
      format.csv {
        send_data(csv_content_for_detail(@traffics),  
                  :type => "text/csv;charset=utf-8; header=present",  
                  :filename => "流量明细_#{Time.now.strftime("%Y%m%d")}.csv")  
      }
    end
  end

  def stat
    set_tab :stat_traffics, :sub_nav
    params[:stat] ||= {}
    params[:stat][:group_by] = 'day' unless ['day', 'week', 'month'].include?(params[:stat][:group_by])
    if params[:stat][:terminal].present? || params[:stat][:terminal_group_id].present?
      @stats = ('TrafficStat' + params[:stat][:group_by].capitalize).constantize
      @stats = @stats.where(terminal_id: params[:stat][:terminal]).order('key DESC') if params[:stat][:terminal].present?
      @stats = @stats.joins(:terminal).where("terminals.terminal_group_id = ?",params[:stat][:terminal_group_id]) if params[:stat][:terminal_group_id].present?
      ['start', 'end'].each do |type|
        param_date = (type + '_date').to_sym
        if params[:stat][param_date].present?
          key = TimeGroup.get_key params[:stat][:group_by], Time.parse(params[:stat][param_date])
          compare_operator = (type == 'start' ? '>' : '<')
          @stats = @stats.where("key #{compare_operator}= ?", key)
        end
      end
    end

    respond_to do |format|
      format.html {
        @stats = @stats.page params[:stat][:page] if @stats
      }
      format.csv {
        @stats = @stats.includes(:terminal).all if @stats
        send_data(csv_content_for_stat(@stats),  
                  :type => "text/csv;charset=utf-8; header=present",  
                  :filename => "流量统计_#{params[:stat][:terminal]}_#{params[:stat][:start_date]}_#{params[:stat][:end_date]}.csv")  
      }
    end
  end

  def search
    set_tab :search_traffics, :sub_nav
    params[:traffic] ||= {}
    end_date_clause = construct_traffics_end_date_clause(params[:traffic][:start_date], params[:traffic][:end_date])
    @terminals = Terminal
    @terminals = @terminals.order('terminals.traffics_updated_at DESC').includes(:traffics).where(end_date_clause)
    @terminals = @terminals.where(id: params[:traffic][:terminal]) unless params[:traffic][:terminal].blank?
    @terminals = @terminals.where(terminal_group_id: params[:traffic][:terminal_group_id]) unless params[:traffic][:terminal_group_id].blank?

    respond_to do |format|
      format.html {
        #@terminals = @terminals.includes(:terminal_group,:terminal_user,:terminal_order).page params[:page]
        @terminals = @terminals.page params[:page]
        @terminals.each do |terminal|
          terminal.total_flow = 0
          terminal.total_flow = terminal.traffics.sum('flow')
        end
      }
      format.csv {
        @terminals = @terminals.includes(:terminal_group).all
        @terminals.each do |terminal|
          terminal.total_flow = 0
          terminal.total_flow = terminal.traffics.sum('flow')
        end
        send_data(csv_content_for_search(@terminals),  
                  :type => "text/csv;charset=utf-8; header=present",  
                  :filename => "设备流量_#{Time.now.strftime("%Y%m%d")}.csv")  
      }
    end
  end

  private

  def setup
    @ways = case params[:action]
    when 'search'
      ["统计","流量明细"]
    when 'stat'
      ["统计","流量统计"]
    end
    @left_panel = "layouts/statistics_left_panel"
  end

  def construct_traffics_end_date_clause start_date, end_date
    statement = []
    params = []
    (statement << 'traffics.end_at >= ?') && (params << start_date) unless start_date.blank?
    (statement << 'traffics.end_at < ?') && (params << 1.days.since(Time.zone.parse(end_date)).strftime('%Y-%m-%d')) unless end_date.blank?

    [statement.join(' AND ')] + params
  end

  def csv_content_for_detail(objs)
	  header = ["\xEF\xBB\xBF终端", "流量", "开始时间", "结束时间", "采集时间"]  
	  csv_content_for(objs, header) do |record|  
	    [  
	      record.device.mac,  
	      (traffics_friendly_format record.flow.to_i),
	      record.start_at.stamp("2013-03-12 22:01:01"),
	      record.end_at.stamp("2013-03-12 22:01:01"),
	      record.created_at.stamp("2013-03-12 22:01:01") 
	    ]
	  end
  end

  def csv_content_for_search(objs)
    header = ["\xEF\xBB\xBF设备组","终端", "流量"]  
    csv_content_for(objs, header) do |record|  
      [
        record.terminal_group.try(:group_name),
        record.mac,  
        (traffics_friendly_format record.total_flow.to_i)
      ]
    end
  end

  def csv_content_for_stat(objs)
    header = ["\xEF\xBB\xBF日期","设备组","终端", "流量"]  
    csv_content_for(objs, header) do |record|  
      [
        record.key,  
        record.terminal.try(:terminal_group).try(:group_name),
        record.terminal.mac,
        (traffics_friendly_format record.flow.to_i)
      ]
    end
  end

  def csv_content_for(objs, header)
    CSV.generate do |csv|  
      csv << header
      objs.each do |record|  
        csv << yield(record)
      end
    end    
  end
end
